package com.example.integration;

import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.integration.ftp.dsl.Ftp;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class MyIntegrationFactory {

  private final DefaultFtpSessionFactory ftpSessionFactory;

  public MyIntegrationFactory(DefaultFtpSessionFactory ftpSessionFactory) {
    this.ftpSessionFactory = ftpSessionFactory;
  }

  @Bean
  public MessageChannel fileChannel() {
    return new DirectChannel();
  }

  @Bean
  @InboundChannelAdapter(value = "fileChannel", poller = @Poller(fixedDelay = "3000"))
  public MessageSource<File> fileMessageSource() {
    FileReadingMessageSource sourceReader = new FileReadingMessageSource();
    sourceReader.setDirectory(new File("C:\\Users\\cwy\\Desktop\\mdb"));
    return sourceReader;
  }

  @Bean
  @ServiceActivator(inputChannel = "fileChannel")
  public MessageHandler fileWritingMessageHandler() {
    FileWritingMessageHandler handler = new FileWritingMessageHandler(new File("E:\\happy"));
    Ftp.outboundAdapter(ftpSessionFactory).remoteDirectory("/log").autoCreateDirectory(true);
    handler.setFileExistsMode(FileExistsMode.APPEND);
    handler.setExpectReply(false);
    return handler;
  }
}
